# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
library(caret)
library(PRROC)
library(tidyverse)
library(pROC)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--pc", default = "", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))
source(str_c(scriptPath, "/fs_parse_config.R"))

parent <- paste0("./")
createWhenNoExist(parent)

breaks <- seq(0, 1, by = 0.2)

fileName <- "Classification_Result.txt"

if (!file.exists(fileName)) {
  quit(status = 0)
}

data <- read_tsv(fileName)
uniqGroup <- unique(data$ClassNote)

x <- data$Value
y <- data$ClassNote

if (length(unique(y)) == 1) {
  quit(status = 0)
}

rocRs <- roc(y, x, ci = T, auc = T, direction = "auto")

auc <- rocRs$auc %>%
  round(3)

rocDf <- tibble(FPR = (1 - rocRs$specificities), Sensitivity = rocRs$sensitivities, Cutoff = rocRs$thresholds,
                Specificity = rocRs$specificities) %>%
  arrange(Sensitivity)

print(rocDf, n = 40)

rocOutDf <- rocDf %>%
  select("Cutoff", "FPR", "Sensitivity") %>%
  arrange(desc(Cutoff))

write.csv(rocOutDf, "ROC_Curve_Data_CV_Overall.csv", row.names = F)

yBreaks <- seq(0, 1, 0.2)

pointData <- coords(rocRs, "best", transpose = T) %>%
  round(3) %>%
  as.data.frame() %>%
  rownames_to_column("Name") %>%
  select(1:2) %>%
  gather("Kind", "Value", -Name) %>%
  spread(Name, "Value")

ci <- rocRs$ci

ci1 <- ci[1] %>%
  round(3)
ci2 <- ci[3] %>%
  round(3)

plotConfigData <- read_tsv(opt$pc, col_names = F, col_types = "cc") %>%
  set_colnames(c("arg", "value"))
fontFamily <- configGet(plotConfigData, "fontFamily")
baseFamily <- fontFamily
if (baseFamily == "SimSun") {
  font_import(paths = c("/usr/share/fonts/myFonts"), recursive = F, prompt = F)
}
height <- configGet(plotConfigData, "height") %>%
  as.numeric()
width <- configGet(plotConfigData, "width") %>%
  as.numeric()

p <-ggplot(data = rocDf, aes(x = FPR, y = Sensitivity)) +
  theme_bw(base_size = 8.8,base_family = baseFamily) +
  theme(plot.title = element_text(size = 14, hjust = 0.5, face = "bold"), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), axis.title.x = element_text(size = 14), axis.title.y = element_text(size = 14),
        axis.text.x = element_text(size = 12), axis.text.y = element_text(size = 12),
        plot.margin = unit(c(1, 0.5, 1, 0.5), "cm"), panel.border = element_rect(size = 0.75),
        legend.text = element_text(size = 9),legend.title = element_text(size = 11)
  ) +
  geom_line() +
  geom_abline(intercept = 0, slope = 1, color = "grey", linetype = 1, size = 0.4) +
  annotate("text", x = 0.5 + 0.01, y = 0.5, label = str_c("AUC:", auc, "(", ci1, ",", ci2, ")"), color = "black",
           hjust = 0, size = 4.3, family = baseFamily) +
  geom_point(data = pointData, aes(x = 1 - specificity, y = sensitivity), size = 1, color = "red") +
  xlab("FPR") +
  geom_text(data = pointData, aes(x = 1 - specificity, y = sensitivity, label = paste0(threshold,
                                                                                       "(", specificity, ",", sensitivity, ")")), color = "black", hjust = 0, vjust = 1, size = 3, nudge_x = 0.015,
            nudge_y = -0.015, family = baseFamily) +
  ylab("Sensitivity") +
  ggtitle(str_c("AUC=", format(auc, digits = 3))) +
  labs(colour = "Cutoff") +
  scale_x_continuous("1 - Specificity", breaks = yBreaks) +
  scale_y_continuous("Sensitivity", breaks = seq(0, 1, 0.2))

p <- getBasicPlotArg(p, plotConfigData)

pdfFileName <- paste0("ROC_Curve_CV_Overall.pdf")
ggsave(limitsize = FALSE,pdfFileName, p, width = width, height = height)










